package utils;

import play.db.jpa.GenericModel;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created by adinlead on 16/11/04.
 */
public class DBQuery {

    public static GenericModel.JPAQuery doQuery(Class<?> clazz, String queryStr, Object[] params) {
        try {
            Object single = clazz.newInstance();
            Method method = clazz.getDeclaredMethod("find", String.class, Array.newInstance(Object.class, 0).getClass());
            return (GenericModel.JPAQuery) method.invoke(single, new Object[]{queryStr, params});
        } catch (Exception e) {
            return null;
        }
    }

    public static GenericModel.JPAQuery doQuery(Class<?> clazz, String queryStr, List params) {
        return doQuery(clazz, queryStr, params.toArray());
    }

    public static GenericModel.JPAQuery doQuery(Class<?> clazz, StringBuilder queryStr, List params) {
        return doQuery(clazz, queryStr.toString(), params.toArray());
    }

    public static Long doCount(Class<?> clazz, String queryStr, Object[] params) {
        try {
            Object single = clazz.newInstance();
            Method method = clazz.getDeclaredMethod("count", String.class, Array.newInstance(Object.class, 0).getClass());
            return (Long) method.invoke(single, new Object[]{queryStr, params});
        } catch (Exception e) {
            return null;
        }
    }

    public static Long doCount(Class<?> clazz, String queryStr, List params) {
        return doCount(clazz, queryStr, params.toArray());
    }

    public static Long doCount(Class<?> clazz, StringBuilder queryStr, List params) {
        return doCount(clazz, queryStr.toString(), params.toArray());
    }
}